package com.web.handle;


import com.core.model.AbstractEntity;
import com.dao.EntityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/6/30
 * Time: 17:29
 * To change this template use File | Settings | File Templates.
 */
@Component
public class RedisTemplateHandle {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;


    public <T extends AbstractEntity> List<T> getInfoList(String key, String hashKey, Class<T> clazz, EntityDao entityDao) {
        List<T> list;
        list = (List<T>) redisTemplate.opsForHash().values(key);
        if (list.isEmpty()) {
            list = entityDao.findAll(clazz, hashKey);
            for (int i = 0; i < list.size(); i++) {
                redisTemplate.opsForHash().put(key, list.get(i).guid(), list.get(i));
            }
        }
        return list;
    }

    public <T extends AbstractEntity> String getInfoString(String key, String hashKey, Class<T> clazz, EntityDao entityDao) {
        String totalPage;
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            totalPage = String.valueOf(redisTemplate.opsForHash().get(key, hashKey));
        } else {
            totalPage = entityDao.findTotalPage(clazz).toString();
            redisTemplate.opsForHash().put(key, hashKey, totalPage);
        }
        return totalPage;
    }

    public <T extends AbstractEntity> T findEntityByGuid(String key, String hashKey, Class<T> clazz, EntityDao entityDao) {
        T t;
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            t = (T) redisTemplate.opsForHash().get(key, hashKey);
        } else {
            t = entityDao.findByGuid(clazz, hashKey);
            putValue(key, hashKey, t);
        }
        return t;
    }

    public <T extends AbstractEntity> void putEntity(String key, String hashKey, T t) throws Exception {
        if (!redisTemplate.opsForHash().hasKey(key, hashKey)) {
            putValue(key, hashKey, t);
        }
    }

    public <T extends AbstractEntity> void updateEntity(String key, String hashKey, T t) {
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            delValue(key, hashKey);
        }
        putValue(key, hashKey, t);
    }

    public <T extends AbstractEntity> void delEntity(String key, String hashKey, T t) throws Exception {
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            delValue(key, hashKey);
        }
    }

    public <T extends AbstractEntity> void putValue(String key, Object hashKey, T t) {
        redisTemplate.opsForHash().put(key, hashKey, t);
    }

    public void delValue(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }


}
